package no.rodland.acc.parsers;

import org.apache.log4j.Logger;
import org.joda.time.DateTime;

import java.util.List;

import no.rodland.acc.db.StoreService;
import no.rodland.acc.model.Bank;
import no.rodland.acc.model.BankType;
import no.rodland.acc.db.FetchService;
import no.rodland.acc.utils.Config;

/**
 * Created by IntelliJ IDEA.
 *
 * @Since: Jun 22, 2010 9:09:10 PM
 * @Author: fmr
 */
public class ExcelBankParser extends AbstractBankParser {
    private static final Logger log = Logger.getLogger(ExcelBankParser.class);

    @Override
    public void configure() {
        this.headerRowRegexp = Config.getProperty("import.budget.header_row_regexp");
        this.separator = Config.getProperty("import.budget.separator");
    }

    public ExcelBankParser(FetchService fetchService,
                           StoreService storeService,
                           DateParser dateParser,
                           NumberParser numberParser,
                           TextDateParser textDateParser) {
        super(fetchService, storeService, dateParser, numberParser, textDateParser);
    }

    @SuppressWarnings({"unchecked"})
    @Override
    public List<Bank> parseLine(String line) throws ParseException {
        try {
            String[] arr = line.split(separator);

            DateTime interestDate = dateParser.parse(arr[0]);
            DateTime accountDate = null;

            String ref = null;
            String btString = arr[1];

            String text = arr[2];

            int i = 3;

            int index = text.indexOf("\"");
            if (index > -1) {
                while (text.indexOf("\"", index + 1) == -1) {
                    text = text + "," + arr[i++];
                }
            }
            text = text.replaceAll("[\"']", "").trim();

            Integer amountOut = numberParser.parse(arr[i++]);
            Integer amountIn = 0;
            if (arr.length > i) {
                amountIn = numberParser.parse(arr[i]);
            }

            String budgeted = "Y";
            String comment = "import fra gammelt budsjett";

            DateTime useDate = textDateParser.parse(text, interestDate);
            BankType bankType = getBankType(btString);

            return makeList(new Bank(interestDate,
                    accountDate,
                    useDate,
                    ref,
                    bankType,
                    text,
                    amountOut,
                    amountIn,
                    bankAccount,
                    budgeted,
                    comment));
        }
        catch (Exception e) {
            log.error("Unable to parse line: " + line, e);
            throw new ParseException("Unable to parse line", line, e);
        }
    }

    @Override
    public String getName() {
        return "Excel konto";
    }
}
